<%@ page import="bean.DB" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>结算页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 60%;
            margin: 0 auto;
            padding: 20px;
        }
        .address-container label {
            font-size: 1.2em;
        }
        .address-container input[type="text"], .address-container input[type="submit"] {
            padding: 10px;
            font-size: 1.1em;
            margin-top: 10px;
        }
        .checkout-button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 1.2em;
            margin-top: 20px;
            cursor: pointer;
            border-radius: 5px;
        }
        .checkout-button:hover {
            background-color: #45a049;
        }
        .cart-summary table {
            width: 100%;
            border-collapse: collapse;
        }
        .cart-summary th, .cart-summary td {
            padding: 10px;
            border: 1px solid #ddd;
        }
        .cart-summary th {
            text-align: left;
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
<div class="container">
    <%
        // 从 session 获取 userId 和收货地址
        String userIdStr = (String) session.getAttribute("userId");
        if (userIdStr == null) {
            System.out.println("<p>用户未登录，无法进行结算。</p>");
        } else {
            // 通过 userId 获取收货地址
            int userId = Integer.parseInt(userIdStr);

            // 假设获取地址的逻辑，通过数据库查询
            String userAddress = ""; // 默认值
            try {
                // 获取数据库连接，假设 DB.createConn() 方法返回连接
                DB db = new DB();
                String getAddressSql = "SELECT address FROM users WHERE id = ?";
                try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(getAddressSql)) {
                    pstmt.setInt(1, userId);
                    ResultSet rs = pstmt.executeQuery();
                    if (rs.next()) {
                        userAddress = rs.getString("address");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 显示收货地址
            if (userAddress != null && !userAddress.isEmpty()) {
    %>
    <h2>当前收货地址: <%= userAddress %></h2>

    <%
        // 获取购物车商品信息并计算总价和总积分
        DB db = new DB();
        double totalAmount = 0.0;
        double totalStars = 0.0; // 初始化总积分
        try {
            String getCartItemsSql = "SELECT p.product_name, ci.quantity, p.price, p.star " +
                    "FROM userCart ci " +
                    "JOIN products p ON ci.product_id = p.id " +
                    "WHERE ci.user_id = ?";
            try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(getCartItemsSql)) {
                pstmt.setInt(1, userId);
                ResultSet cartItemsRs = pstmt.executeQuery();
                // 显示购物车项
                System.out.println("<table class='cart-summary'>");
                System.out.println("<tr><th>商品名称</th><th>数量</th><th>单价</th><th>积分</th><th>总价</th></tr>");
                while (cartItemsRs.next()) {
                    String productName = cartItemsRs.getString("product_name");
                    int quantity = cartItemsRs.getInt("quantity");
                    double price = cartItemsRs.getDouble("price");
                    double star = cartItemsRs.getDouble("star"); // 获取积分值
                    double itemTotal = price * quantity;
                    double itemTotalStars = star * quantity; // 商品积分总值 = 单件积分 * 数量
                    totalAmount += itemTotal;
                    totalStars += itemTotalStars; // 累加积分总值
                    System.out.println("<tr>");
                    System.out.println("<td>" + productName + "</td>");
                    System.out.println("<td>" + quantity + "</td>");
                    System.out.println("<td>" + price + "</td>");
                    System.out.println("<td>" + itemTotalStars + "</td>");
                    System.out.println("<td>" + itemTotal + "</td>");
                    System.out.println("</tr>");
                }
                System.out.println("</table>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    %>

    <h3>购物车总价: <%= totalAmount %> 元</h3>
    <h3>购物车总积分: <%= totalStars %> 分</h3>

    <form action="./updateAddressServlet" method="post">
        <label>更改收货地址：</label>
        <input type="text" id="address1" name="address" value="<%= userAddress %>" placeholder="请输入新的收货地址">
        <input type="submit" value="更改收货地址">
    </form>
    <%
    } else {
    %>
    <p>您尚未设置收货地址。请填写您的收货地址。</p>
    <form action="./updateAddressServlet" method="post">
        <label>收货地址：</label>
        <input type="text" id="address2" name="address" placeholder="请输入您的收货地址">
        <input type="submit" value="保存收货地址">
    </form>
    <%
            }
        }
    %>

    <!-- 结算按钮 -->
    <form action="./checkoutServlet" method="post">
        <input type="submit" class="checkout-button" value="确认订单并现金结算">
    </form>
    <form action="./checkOutByStarServlet" method="post">
        <input type="submit" class="checkout-button" value="确认订单并积分结算">
    </form>
</div>
</body>
</html>